package com.mass.waybill.voucher.controller;

import com.mass.core.sys.dict.model.SysDictVal;
import com.mass.core.sys.dict.service.SysDictValService;
import com.mass.core.sys.user.model.SysUser;
import com.mass.core.utils.AjaxResponse;
import com.mass.core.utils.ExcelUtil;
import com.mass.core.utils.NumberUtils;
import com.mass.waybill.order.model.WbShippingOrder;
import com.mass.waybill.records.service.WbSterilisationRecordsService;
import com.mass.waybill.voucher.model.WbVoucher;
import com.mass.waybill.voucher.service.WbVoucherService;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.constraints.NotNull;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: ZSX
 * @Description: 收款单
 */
@RestController
@RequestMapping("/wb/voucher")
public class WbVoucherController {

    @Autowired
    private WbVoucherService wbVoucherService;
    @Autowired
    private SysDictValService sysDictValService;
    @Autowired
    private WbSterilisationRecordsService wbSterilisationRecordsService;
    /**
     * 根据订单编号查询订单明细
     *
     * @param orderCode
     * @return
     */
    @GetMapping("/findByOrderCode")
    public AjaxResponse findByOrderCode(String orderCode) {
        List<WbVoucher> list = wbVoucherService.findByOrderCode(orderCode);
        return AjaxResponse.success("ok", list, (long) list.size(), 1);
    }

    /**
     * 导出收款统计表
     *
     * @param wbVoucher
     */
    @GetMapping("/exportRecords")
    public void exportRecords(WbVoucher wbVoucher, HttpServletResponse response) {
        AjaxResponse ajaxResponse = wbVoucherService.selectPage(wbVoucher, null, null);
        if (!ObjectUtils.isEmpty(ajaxResponse.getData())) {
            //查询所有数据字典
            List<SysDictVal> sysDictValList = sysDictValService.getByTypeCode(null,null,null, null, null, null);
            List<WbVoucher> wbVoucherList = (List<WbVoucher>) ajaxResponse.getData();
            //数据字典 Map  key  字典编码  value  字典值
            Map<String, String> dictMap = new HashMap<String, String>();
            for (SysDictVal sysDictVal : sysDictValList) {
                dictMap.put(sysDictVal.getValCode(), sysDictVal.getValName());
            }
            //表头
            String[] titles = {"序号", "结算编号", "付款日期", "收款账户", "付款人", "付款金额", "已核销金额", "余额", "备注"};
            //文件名
            String fileName = "收款统计表";
            ServletOutputStream out = null;
            try {
                HSSFWorkbook workbook = new HSSFWorkbook();
                HSSFSheet sheet = workbook.createSheet();
                int colNum = titles.length;
                int rowNO = 0;
                ExcelUtil.createExcelRow(workbook, sheet, rowNO, -1, colNum, "收款统计表");
                rowNO = rowNO + 1;
                ExcelUtil.createExcelRow(workbook, sheet, rowNO, 200, colNum, "制 表 日 期: " + (new SimpleDateFormat("yyyy-MM-dd")).format(new Date()), 180, "normal", "right");
                ++rowNO;
                ExcelUtil.createColumnHeader(workbook, sheet, rowNO, 300, titles);
                ++rowNO;
                String[][] strings = new String[wbVoucherList.size()][titles.length];
                //收款总金额   已核销总金额
                Double accountsReceivableAmount = 0.00, sterilisationAmount = 0.00;
                for (int i = 0; i < wbVoucherList.size(); ++i) {
                    WbVoucher voucher = wbVoucherList.get(i);
                    strings[i][0] = (i + 1) + "";               //序号
                    strings[i][1] = voucher.getSettlementNumber();  //结算编号
                    strings[i][2] = voucher.getDateReceipt();       //付款日期
                    strings[i][3] = !ObjectUtils.isEmpty(dictMap.get(voucher.getPaymentAccount())) ? dictMap.get(voucher.getPaymentAccount()) : "—";               //收款账户
                    if (!ObjectUtils.isEmpty(voucher.getDrawee())) {
                        strings[i][4] = voucher.getDrawee();        //付款人
                    } else {
                        strings[i][4] = "—";
                    }
                    strings[i][5] = String.format("%.2f", Double.parseDouble(voucher.getPaymentAmount().trim())); //收款金额
                    accountsReceivableAmount = NumberUtils.add(accountsReceivableAmount, Double.parseDouble(voucher.getPaymentAmount().trim()));

                    if (!ObjectUtils.isEmpty(voucher.getAmountCancelVerification())) {
                        strings[i][6] = String.format("%.2f", Double.parseDouble(voucher.getAmountCancelVerification().trim()));
                        //已收金额
                        double yue = NumberUtils.subtract(Double.parseDouble(voucher.getPaymentAmount().trim()), Double.parseDouble(voucher.getAmountCancelVerification().trim()));  //余额
                        strings[i][7] = String.format("%.2f", yue);              //余额
                        sterilisationAmount = NumberUtils.add(sterilisationAmount, Double.parseDouble(voucher.getAmountCancelVerification().trim()));
                    } else {
                        strings[i][6] = "0.00";
                        strings[i][7] = strings[i][5];               //余额
                    }
                }
                sheet = ExcelUtil.createColumnData(workbook, sheet, rowNO, strings, wbVoucherList.size() + 3);
                //最后一行
                HSSFRow lastRow = sheet.createRow((short) (sheet.getLastRowNum() + 1));
                lastRow.createCell(1).setCellValue(new HSSFRichTextString("合计："));
                lastRow.createCell(5).setCellValue(new HSSFRichTextString(String.format("%.2f", accountsReceivableAmount)));
                lastRow.createCell(6).setCellValue(new HSSFRichTextString(String.format("%.2f", sterilisationAmount)));
                lastRow.createCell(7).setCellValue(new HSSFRichTextString(String.format("%.2f", NumberUtils.subtract(accountsReceivableAmount, sterilisationAmount))));
                // ExcelUtil.createSummaryRow(workbook, sheet, colNum, "行数合计：" + strings.length, 180, "normal", "right");

                fileName = fileName + (new SimpleDateFormat("yyyyMMddHHmmss")).format(new Date());
                out = response.getOutputStream();
                response.setContentType("application/ms-excel;charset=UTF-8");
                response.setHeader("Content-disposition", "attachment;filename=" + new String(fileName.getBytes("utf-8"), "ISO8859-1") + ".xls");
                workbook.write(out);
            } catch (Exception var35) {
                var35.printStackTrace();
            } finally {
                try {
                    out.close();
                } catch (IOException var34) {
                    var34.printStackTrace();
                }

            }
        }
    }

    /**
     * 导出订单冲销明细
     *
     * @param settlementNumber
     * @return
     */
    @RequestMapping("/exportInfo")
    public void findOrderBySettlementNumber(String settlementNumber, HttpServletResponse response) {
        List<WbShippingOrder> wbShippingOrderList = wbSterilisationRecordsService.findOrderBySettlementNumber(settlementNumber, null);
        //查询所有数据字典
        List<SysDictVal> sysDictValList = sysDictValService.getByTypeCode(null,null,null, null, null, null);
        //数据字典 Map  key  字典编码  value  字典值
        Map<String, String> dictMap = new HashMap<String, String>();
        for (SysDictVal sysDictVal : sysDictValList) {
            dictMap.put(sysDictVal.getValCode(), sysDictVal.getValName());
        }
        //表头
        String[] titles = {"序号", "订单编号", "业务员", "下单日期", "业务类型", "品名", "箱型", "箱号", "发货单位", "装货地点", "发出", "到站", "收货人", "结算人", "应收金额", "冲销金额"};
        //文件名
        String fileName = "冲销明细";
        ServletOutputStream out = null;
        try {
            HSSFWorkbook workbook = new HSSFWorkbook();
            HSSFSheet sheet = workbook.createSheet();
            int colNum = titles.length;
            int rowNO = 0;
            ExcelUtil.createExcelRow(workbook, sheet, rowNO, -1, colNum, "冲销明细");
            rowNO = rowNO + 1;
            ExcelUtil.createExcelRow(workbook, sheet, rowNO, 200, colNum, "制 表 日 期: " + (new SimpleDateFormat("yyyy-MM-dd")).format(new Date()), 180, "normal", "right");
            ++rowNO;
            ExcelUtil.createColumnHeader(workbook, sheet, rowNO, 300, titles);
            ++rowNO;
            String[][] strings = new String[wbShippingOrderList.size()][titles.length];
            //应付金额   实付金额
            Double accountsReceivableAmount = 0.00, sterilisationAmount = 0.00;
            for (int i = 0; i < wbShippingOrderList.size(); ++i) {
                WbShippingOrder order = wbShippingOrderList.get(i);
                strings[i][0] = (i + 1) + "";               //序号
                strings[i][1] = order.getOrderCode();        //订单编号
                strings[i][2] = order.getSalesman();        //业务员
                strings[i][3] = order.getOrderDate();       //下单日期
                strings[i][4] = !ObjectUtils.isEmpty(dictMap.get(order.getBusinessTypes())) ? dictMap.get(order.getBusinessTypes()) : "—";               //业务类型
                strings[i][5] = !ObjectUtils.isEmpty(dictMap.get(order.getOfTheGoods())) ? dictMap.get(order.getOfTheGoods()) : "—";               //品名
                strings[i][6] = !ObjectUtils.isEmpty(dictMap.get(order.getaBox())) ? dictMap.get(order.getaBox()) : "—"; //箱型
                strings[i][7] = !ObjectUtils.isEmpty(order.getCartonNo()) ? order.getCartonNo() : "";               //箱号
                strings[i][8] = !ObjectUtils.isEmpty(dictMap.get(order.getDeliveryUnit())) ? dictMap.get(order.getDeliveryUnit()) : "—";//发货单位
                strings[i][9] = !ObjectUtils.isEmpty(dictMap.get(order.getStandby1())) ? dictMap.get(order.getStandby1()) : "—";//装货地点
                strings[i][10] = !ObjectUtils.isEmpty(dictMap.get(order.getaStation())) ? dictMap.get(order.getaStation()) : "—";///发出
                strings[i][11] = !ObjectUtils.isEmpty(dictMap.get(order.getArriveStation())) ? dictMap.get(order.getArriveStation()) : "—"; //到站
                strings[i][12] = !ObjectUtils.isEmpty(dictMap.get(order.getReceivingUnit())) ? dictMap.get(order.getReceivingUnit()) : "—";//收货人
                strings[i][13] = !ObjectUtils.isEmpty(dictMap.get(order.getSettlementPeople())) ? dictMap.get(order.getSettlementPeople()) : "—";//结算人
                strings[i][14] = !ObjectUtils.isEmpty(order.getAccountsReceivableAmount()) ? order.getAccountsReceivableAmount(): "—";//结算人
                strings[i][15] = !ObjectUtils.isEmpty(order.getSterilisationAmount()) ? dictMap.get(order.getSterilisationAmount()) : "—";//结算人

            }
            sheet = ExcelUtil.createColumnData(workbook, sheet, rowNO, strings, wbShippingOrderList.size() + 3);
            ExcelUtil.createSummaryRow(workbook, sheet, colNum, "行数合计：" + strings.length, 180, "normal", "right");

            fileName = fileName + (new SimpleDateFormat("yyyyMMddHHmmss")).format(new Date());
            out = response.getOutputStream();
            response.setContentType("application/ms-excel;charset=UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + new String(fileName.getBytes("utf-8"), "ISO8859-1") + ".xls");
            workbook.write(out);
        } catch (
                Exception var35) {
            var35.printStackTrace();
        } finally {
            try {
                out.close();
            } catch (IOException var34) {
                var34.printStackTrace();
            }

        }
    }


    /**
     * 增加
     *
     * @param wbVoucher
     * @return
     */
    @ApiOperation(value = "添加一个实例", notes = "添加wbVoucher")
    @PostMapping("/insert")
    public AjaxResponse insert(WbVoucher wbVoucher, HttpSession session) {
        Object object = session.getAttribute("sysUser");
        if (!ObjectUtils.isEmpty(object)) {
            SysUser sysUser = (SysUser) object;
            wbVoucher.setThePayee(sysUser.getName());
        } else {
            return AjaxResponse.success("未登录！");
        }
        int number = wbVoucherService.insert(wbVoucher);
        return AjaxResponse.success(number);
    }

    /**
     * 删除
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "添加一个实例", notes = "删除wbVoucher")
    @ApiImplicitParam(name = "id", value = "id", paramType = "query", dataType = "Long", required = true)
    @PostMapping("/delete")
    public AjaxResponse delete(@NotNull(message = "id不能为空") Long id) {
        int number = wbVoucherService.delete(id);
        return AjaxResponse.success(number);
    }

    /**
     * 修改
     *
     * @param wbVoucher
     * @return
     */
    @ApiOperation(value = "修改", notes = "修改wbVoucher")
    @PostMapping("/update")
    public AjaxResponse update(WbVoucher wbVoucher) {
        int number = wbVoucherService.update(wbVoucher);
        return AjaxResponse.success(number);
    }

    /**
     * 通过id查找
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "根据ID查找实例", notes = "通过id查找详情")
    @ApiImplicitParam(name = "id", value = "id", paramType = "query", dataType = "Long", required = true)
    @PostMapping("/selectById")
    public AjaxResponse selectById(@NotNull(message = "id不能为空") Long id) {
        WbVoucher wbVoucher = wbVoucherService.selectById(id);
        return AjaxResponse.success(wbVoucher);
    }

    /**
     * 分页条件查找
     *
     * @param input 输入对象
     * @return
     */
    @ApiImplicitParams({
            @ApiImplicitParam(value = "列表查询", paramType = "query", required = false, dataType = "WbVoucher"),
            @ApiImplicitParam(name = "page", value = "当前页", paramType = "query", required = true, dataType = "Integer"),
            @ApiImplicitParam(name = "limit", value = "查询行", paramType = "query", required = true, dataType = "Integer")
    })
    @GetMapping(value = "/selectPage")
    public AjaxResponse selectPage(WbVoucher wbVoucher, Integer page, Integer limit) {
        return wbVoucherService.selectPage(wbVoucher, page, limit);
    }

    @PostMapping("/deleteByIds")
    public AjaxResponse deleteByIds(@RequestParam(value = "ids[]") List<Long> ids) {
        return AjaxResponse.success(wbVoucherService.deleteByIds(ids));
    }
}
